package yz.cp.back.auth.authenticator;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import yz.cp.back.auth.security.SecUser;
import yz.cp.back.auth.security.handler.OauthTokenService;
import yz.cp.back.auth.sign.SignRequestUtils;
import yz.cp.back.common.integration.IntegrationAuthentication;
import yz.cp.back.common.integration.authenticator.AbstractPreparableIntegrationAuthenticator;
import yz.cp.back.common.res.ApiResult;
import yz.cp.back.common.service.AESService;
import yz.cp.back.common.utils.PasswordUtil;
import yz.cp.back.common.utils.ServletUtils;
import yz.cp.back.s.entity.SysUser;
import yz.cp.back.s.service.ISysUserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * 默认登录处理
 *
 * @author wind
 * @date 2018-3-31
 **/
@Component
@Primary
@Slf4j
public class UsernamePasswordAuthenticator extends AbstractPreparableIntegrationAuthenticator {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private OauthTokenService oauthTokenService;
    @Autowired
    private AESService aesService;

    @Override
    public SecUser authenticate(IntegrationAuthentication integrationAuthentication) {
        SysUser user = userService.findByUsername(integrationAuthentication.getUsername());
        String password=integrationAuthentication.getAuthParameter("password");
        if (user == null) {
            throw new InternalAuthenticationServiceException("登录失败");
        }
        String passType=integrationAuthentication.getAuthParameter("pass_type");
        String decodePass="";
        if(StringUtils.equalsAnyIgnoreCase(passType,"AES")){
           decodePass=aesService.decode(password);
            if(!StringUtils.equalsAnyIgnoreCase(decodePass,user.getPassword())){
                throw new InternalAuthenticationServiceException("登录失败");
            }
        }else  if(StringUtils.equalsAnyIgnoreCase(passType,"BCrypt")){
            if(!PasswordUtil.matches(password,user.getPassword())){
                throw new InternalAuthenticationServiceException("登录失败");
            }
        }else {
            if(!PasswordUtil.matches(password,user.getPassword())){
                throw new InternalAuthenticationServiceException("登录失败");
            }
        }

        SecUser secUse= new SecUser(user.getId(), user.getUsername(), user.getPassword(),
                Lists.newArrayList(), true,
                true, true,
                true).checkPass(true);
        Map map= Maps.newHashMap();
        map.put("roles",user.getRoles());
        map.put("permissions",user.getPermissions());
        secUse.setData(map);
        return secUse;

    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {
        if(integrationAuthentication.getAuthParameters()!=null&&integrationAuthentication.getAuthParameters().size()>0){
            String  customize=integrationAuthentication.getAuthParameter("customize");
            boolean flag1=StringUtils.contains(customize,"true");
            if(!flag1){
                return;
            }
            boolean flag = SignRequestUtils.valid(integrationAuthentication.getStringMap());
            if(!flag){
                throw new InternalAuthenticationServiceException("校验失败");
            }
        }
    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.isEmpty(integrationAuthentication.getAuthType());
    }

    @Override
    public boolean complete(HttpServletRequest request, HttpServletResponse response, Authentication auth, AuthenticationException e) {
        if(e!=null){
            return false;
        }else {
            JSONObject jsonObject = oauthTokenService.oauthTokenJSON();
            ServletUtils.renderResult(response, ApiResult.Custom().success().add(jsonObject));
            return true;
        }

    }
}
